import { HttpLink } from "apollo-link-http";
import ApolloClient from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { setContext } from "apollo-link-context";

const getHeaders = (headers = {}) => {
  const token = localStorage.getItem("apollo-token");
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }
  return headers;
};

const link = new HttpLink({
  uri: "http://linyu.dynv6.net:10011/v1/graphql"
});

const authLink = setContext((_, { headers }) => {
  return {
    headers: getHeaders(headers)
  };
});

const defaultClient = new ApolloClient({
  link: authLink.concat(link),
  cache: new InMemoryCache()
});

export default defaultClient;